package zd.cornermemory.ui;

import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import greendao.CjDao;
import zd.cornermemory.App;
import zd.cornermemory.R;
import zd.cornermemory.db.Cj;
import zd.cornermemory.db.GreenDaoManager;
import zd.cornermemory.utils.SpKey;
import zd.cornermemory.utils.Statistics;
import zd.cornermemory.utils.Utils;
import zd.cornermemory.view.CustomDialog;

public class CjDetailActivity extends BaseActivity implements View.OnClickListener{
    private Cj cj;
    private int position;
    private TextView position_text;

    private TextView singtime;
    private TextView date;
    private TextView scrameble;

    private TextView  no;
    private ImageView no_image;
    private TextView  add2;
    private ImageView add2_image;
    private TextView  dnf;
    private ImageView dnf_image;

    private RelativeLayout remark_layout;
    private TextView       remark_text;

    private TextView copy;
    private TextView delete;

    private Toast copyToast;
    private int currentPos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cj_detail);
        cjDao =  GreenDaoManager.getInstance().getNewSession().getCjDao();
        findViews();
        initData();
        setEvent();
        copyToast = Toast.makeText(mContext, getString(R.string.copied), Toast.LENGTH_SHORT);
        setBackImage();
    }

    private void setEvent() {
        no.setOnClickListener(this);
        add2.setOnClickListener(this);
        dnf.setOnClickListener(this);
        remark_layout.setOnClickListener(this);
        copy.setOnClickListener(this);
        delete.setOnClickListener(this);
    }

    private void initData() {
        hide();
        Bundle bundle = getIntent().getExtras();
        cj = (Cj)bundle.getSerializable("bean");
        position = bundle.getInt("position");
        currentPos = bundle.getInt("currentPos");
        position_text.setText("#"+position);

        setTimeStr();

        String dateStr = Statistics.handleLongDate(cj.getDate(),0);
        date.setText(dateStr);
        scrameble.setText(cj.getCode());
        remark_text.setText(cj.getEtnote());
    }
    private int status = 0;
    private void setTimeStr() {
        String timeStr = "";
        int t = cj.getSingTime().intValue();
        if (cj.getStatus() == 2) {
            dnf_image.setVisibility(View.VISIBLE);
            timeStr = "DNF (" + Statistics.timeToString(t) + ")";
        } else if (cj.getStatus() == 1) {
            add2_image.setVisibility(View.VISIBLE);
            timeStr = Statistics.timeToString(t) + "+";
        } else {
            no_image.setVisibility(View.VISIBLE);
            timeStr = Statistics.timeToString(t);
        }
        status = cj.getStatus();
        singtime.setText(timeStr);
    }

    private void findViews() {
        position_text = findViewById(R.id.position_text);
        singtime = findViewById(R.id.singtime);
        date = findViewById(R.id.date);
        scrameble = findViewById(R.id.scrameble);
        no = findViewById(R.id.no);
        no_image = findViewById(R.id.no_image);
        add2 = findViewById(R.id.add2);
        add2_image = findViewById(R.id.add2_image);
        dnf = findViewById(R.id.dnf);
        dnf_image = findViewById(R.id.dnf_image);
        remark_layout = findViewById(R.id.remark_layout);
        remark_text = findViewById(R.id.remark_text);
        copy = findViewById(R.id.copy);
        delete = findViewById(R.id.delete);
    }


    private void hide(){
        no_image.setVisibility(View.GONE);
        add2_image.setVisibility(View.GONE);
        dnf_image.setVisibility(View.GONE);
    }
    private CjDao cjDao;
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(SpKey.UPDATE_CJ);
        switch (view.getId()) {
            case R.id.no:
                if (status != 0) {
                    hide();
                    no_image.setVisibility(View.VISIBLE);
                    cj.setStatus(0);
                    if (status == 1) {//+2 改无
                        long time = cj.getSingTime()-2000;
                        cj.setSingTime(time);
                    }

                    List<Cj> cjList = App.getInstance().getAllCjMap().get(currentPos);
                    long cjId = cj.getId();
                    for (Cj c : cjList) {
                        long currentId = c.getId();
                        if (cjId==currentId) {
                            c.setStatus(cj.getStatus());
                            c.setSingTime(cj.getSingTime());
                            break;
                        }
                    }

                    setTimeStr();
                    cjDao.update(cj);
                    status = 0;
                    //延时通知，防卡顿
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(SpKey.DELETE_CJ);
                            sendBroadcast(intent);
                        }
                    }, 500);
                    finish();
                }

                break;
            case R.id.add2:
                if (status != 1) {
                    hide();
                    add2_image.setVisibility(View.VISIBLE);

                    cj.setStatus(1);
                    long time = cj.getSingTime()+2000;
                    cj.setSingTime(time);
                    cjDao.update(cj);

                    List<Cj> cjList = App.getInstance().getAllCjMap().get(currentPos);
                    long cjId = cj.getId();
                    for (Cj c : cjList) {
                        long currentId = c.getId();
                        if (cjId==currentId) {
                            c.setStatus(cj.getStatus());
                            c.setSingTime(cj.getSingTime());
                            break;
                        }
                    }

                    setTimeStr();
                    status = 1;
                    //延时通知，防卡顿
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(SpKey.DELETE_CJ);
                            sendBroadcast(intent);
                        }
                    }, 500);
                    finish();
                }

                break;
            case R.id.dnf:
                if (status != 2) {
                    hide();
                    dnf_image.setVisibility(View.VISIBLE);
                    cj.setStatus(2);
                    if (status == 1) {
                        long time = cj.getSingTime()-2000;
                        cj.setSingTime(time);
                    }
                    cjDao.update(cj);

                    List<Cj> cjList = App.getInstance().getAllCjMap().get(currentPos);
                    long cjId = cj.getId();
                    for (Cj c : cjList) {
                        long currentId = c.getId();
                        if (cjId==currentId) {
                            c.setStatus(cj.getStatus());
                            c.setSingTime(cj.getSingTime());
                            break;
                        }
                    }

                    setTimeStr();
                    status = 2;
                    //延时通知，防卡顿
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(SpKey.DELETE_CJ);
                            sendBroadcast(intent);
                        }
                    }, 500);
                    finish();
                }
                break;
            case R.id.remark_layout:
                inputRemark();
                break;
            case R.id.copy:
                if(Build.VERSION.SDK_INT > 11) {
                    android.content.ClipboardManager clip = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    clip.setPrimaryClip(ClipData.newPlainText("text", cj.getCode()));
                }
                else {
                    android.text.ClipboardManager clip = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    clip.setText(cj.getCode());
                }
                copyToast.show();
                break;
            case R.id.delete:
                if(!isFastDoubleClick()){
                    cjDao.delete(cj);
                    List<Cj> mapList = App.getInstance().getAllCjMap().get(currentPos);
                    long deleteId = cj.getId();
                    for (Cj c : mapList) {
                        long id = c.getId();
                        if (id == deleteId) {
                            mapList.remove(c);
                            break;
                        }
                    }
                    //延时通知，防卡顿
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(SpKey.DELETE_CJ);
                            sendBroadcast(intent);
                        }
                    }, 500);
                    finish();
                }
                break;

        }
    }

    private View view;
    private EditText editText;
    private void inputRemark() {
        LayoutInflater factory = LayoutInflater.from(mContext);
        int layoutId = R.layout.edit_remark_layout;
        view = factory.inflate(layoutId, null);
        editText = (EditText) view.findViewById(R.id.edit_text);
        if (!TextUtils.isEmpty(cj.getEtnote())) {
            editText.setText(cj.getEtnote());
            editText.setSelection(cj.getEtnote().length());
        }
        new CustomDialog.Builder(mContext).setTitle(getString(R.string.noted)).setView(view)
                .setPositiveButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Utils.hideKeyboard(editText);

                    }
                }).setNegativeButton(getString(R.string.have), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String remarkStr = editText.getText().toString();
                if (TextUtils.isEmpty(remarkStr)) {
                    remarkStr = "";
                }
                remark_text.setText(remarkStr);
                cj.setEtnote(remarkStr);
                cjDao.update(cj);

                List<Cj> cjList = App.getInstance().getAllCjMap().get(currentPos);
                long cjId = cj.getId();
                for (Cj c : cjList) {
                    long currentId = c.getId();
                    if (cjId==currentId) {
                        c.setEtnote(remarkStr);
                        break;
                    }
                }
                Utils.hideKeyboard(editText);
                //延时通知，防卡顿
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(SpKey.DELETE_CJ);
                        sendBroadcast(intent);
                    }
                }, 500);
                finish();
            }
        }).show();
        Utils.showKeyboard(editText);
    }
    private static final int TIME = 1000;
    private static long lastClickTime = 0;
    /**
     * 处理快速双击，多击事件，在TIME时间内只执行一次事件
     *
     * @return
     */
    public static boolean isFastDoubleClick() {
        long currentTime = System.currentTimeMillis();
        long timeInterval = currentTime - lastClickTime;
        if (0 < timeInterval && timeInterval < TIME) {
            return true;
        }
        lastClickTime = currentTime;
        return false;
    }
}
